import { useWebSocket } from '@vueuse/core'
import type { ControlWsResponse } from '@/types/ws'

type UseControlWebsocketOptions = {
  url?: string
  onMessage?: (data: ControlWsResponse) => void
  onAlreadyConnected?: () => void
}

const defaultUrl = 'ws://localhost:8765'

export const useControlWebsocket = (options?: UseControlWebsocketOptions) => {
  const url = options?.url || defaultUrl

  const onConnected = () => {
    console.log(`${url} 连接成功`)
  }

  const onDisconnected = (ws: WebSocket, event: CloseEvent) => {
    console.log(`${url} 连接关闭`, event)
  }

  const onError = (ws: WebSocket, event: Event) => {
    console.info(`${url} 连接失败：`, event)
  }

  const onMessage = (ws: WebSocket, event: MessageEvent) => {
    console.log(`${url} 接收消息：`, event)
    try {
      const response: ControlWsResponse = JSON.parse(event.data)
      if (response.status === 'success') {
        if (options && options.onMessage) {
          options.onMessage(response)
        }
      } else {
        ElMessage.error(response.message || '服务器返回错误')
        if (response.message.indexOf('is already running') !== -1) {
          options?.onAlreadyConnected?.()
        }
      }
    } catch (e) {
      console.error(`${url} 返回非JSON文本消息，错误信息：`, e)
    }
  }

  const { open, send, close, status } = useWebSocket(url, {
    onConnected,
    onDisconnected,
    onError,
    onMessage,
    autoReconnect: {
      retries: 5,
      delay: 10 * 1000,
      onFailed: () => {
        ElMessage.error(`${url} 连接重试失败，请检查网络或服务器状态`)
      },
    },
  })

  return {
    open,
    close,
    send,
    status,
  }
}
